//
//  DetailRecordViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 08.05.25.
//

import Foundation
class DetailRecordViewModel : KoiAccountingBaseViewModel {
    
    @Published var detail: AccountingDetailCombine
    @Published var updateState: String = ""
    @Published var deleteState: String = ""
    @Published var selectedDate: Date = Date()
    @Published var selectedBook: AccountingBook? = nil
    private let detailDao = KoiAccountingDB.standard.getDetailDao()
    private let detailRepo = DetailRepo()
    
    init(detail: AccountingDetailCombine) {
        self.detail = detail
        self.selectedBook = detail.book
    }
    
    func loadDetail() {
        let recordId = detail.detail.recordId ?? ""
        let bookId = selectedBook?.bookId ?? self.bookId
        asyncBackground {
            let result = self.detailRepo.loadDetail(recordId: recordId, uid: self.uid, bookId: bookId)
            self.asyncMain {
                self.detail = result!
            }
        }
    }
    
    func updateCategory(selectedCategory: AccountingCategory) {
        var detail = detail.detail
        asyncBackground {
            detail.cid = selectedCategory.cid
            self.detailDao.updateRecord(detail: detail)
            self.asyncMain {
                self.updateState = "success"
            }
        }
    }
    
    func updateDate(newDate: Date) {
        var detail = detail.detail
        asyncBackground {
            detail.date = newDate.toISODateString()
            self.detailDao.updateRecord(detail: detail)
            self.asyncMain {
                self.updateState = "success"
            }
        }
    }
    
    func delete(detail: AccountingDetailCombine?) {
        guard let detail = detail else { return }
        asyncBackground {
            self.detailDao.delete(recordId: detail.detail.recordId, uid: self.uid, bookId: self.bookId)
            self.asyncMain {
                self.deleteState = "success"
            }
        }
    }
}
